package exogwt.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.rpc.ServiceDefTarget;
import com.google.gwt.user.client.DOM;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Exogwt implements EntryPoint {
    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {
        final PasswordTextBox txtPassword = new PasswordTextBox();
        final TextBox txtLogin = new TextBox();
        final Button btnLogin = new Button("Login");
        final Label label = new Label();
        final AsyncCallback myAsyncCallback = new MyAsyncCallback(label);

        btnLogin.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                getExogwtService().login(txtLogin.getText(),
                            txtPassword.getText(), myAsyncCallback);
            }
        });

        VerticalPanel loginPanel = new VerticalPanel();
        loginPanel.add(txtLogin);
        loginPanel.add(txtPassword);
        loginPanel.add(btnLogin);

        // Assume that the host HTML has elements defined whose
        // IDs are "slot1", "slot2".  In a real app, you probably would not want
        // to hard-code IDs.  Instead, you could, for example, search for all
        // elements with a particular CSS class and replace them with widgets.
        //
        RootPanel.get("slot1").add(loginPanel);
        RootPanel.get("slot2").add(label);
    }

    static class MyAsyncCallback implements AsyncCallback {
        public void onSuccess(Object object) {
            DOM.setInnerHTML(label.getElement(), object.toString());
        }

        public void onFailure(Throwable throwable) {
            label.setText("Failed to receive answer from server: "
                    + throwable.getMessage());
        }

        Label label;

        public MyAsyncCallback(Label label) {
            this.label = label;
        }
    }

    private static ExogwtServiceAsync exogwtService;
    protected static synchronized ExogwtServiceAsync getExogwtService() {
            if (exogwtService == null) {
                //noinspection NonJREEmulationClassesInClientCode
                exogwtService = (ExogwtServiceAsync) GWT.create(ExogwtService.class);
                ((ServiceDefTarget) exogwtService).setServiceEntryPoint(
                        GWT.getModuleBaseURL() + "/ExogwtService");
            }
            return exogwtService;        
    }
}
